package com.jxb.netty;

import com.jxb.netty.rocketmqNetty.serializable.SerializeType;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.EventExecutorGroup;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static io.netty.util.CharsetUtil.UTF_8;

public class NettyRemotingClient {

    private final int port;
    private final String host;
    private final String clientName;

    public ChannelWrapper channelWrapper;

    public NettyRemotingClient(String host, int port, String clientName) {
        this.port = port;
        this.host = host;
        this.clientName = clientName;
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyRemotingClient("127.0.0.1",9876,"").start();
    }

    public void start() throws InterruptedException {
        //线程组
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host,port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new NettyEncoder())
                                    .addLast(new NettyDecoder())
                                    .addLast(new IdleStateHandler(0, 0, 120))
                                    .addLast(new EchoClientHandler());
                        }
                    });
            ChannelFuture sync = b.connect().sync();
            System.out.println(clientName+"connect ... ...");
            channelWrapper = new ChannelWrapper(sync);
//            doWrite(sync.channel());
//            sync.channel().closeFuture().sync();
        }finally {
//            group.shutdownGracefully().sync();
        }
    }

    private void doWrite(Channel channel) {
        RemotingCommand remotingCommand = new RemotingCommand();
        remotingCommand.setCode(0);
        String s = "123";
        remotingCommand.setBody(s.getBytes(StandardCharsets.UTF_8));
        remotingCommand.setLanguage(LanguageCode.JAVA);
        remotingCommand.setRemark("123");
        remotingCommand.setExtFields(new HashMap<>());
        remotingCommand.setFlag(1);
        remotingCommand.setOpaque(1);
        remotingCommand.setVersion(1);
        remotingCommand.setSerializeTypeCurrentRPC(SerializeType.ROCKETMQ);
        channel.writeAndFlush(remotingCommand);
    }

    private class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
            System.out.println("client Accept"+msg.toString(UTF_8));
            //关闭连接
//            ctx.close();
        }

        /*channel活跃后，做业务处理*/
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
//            ctx.writeAndFlush(Unpooled.copiedBuffer(
//                    "123111111111111111", CharsetUtil.UTF_8));
//            //        ctx.pipeline().write()
//            //        ctx.channel().write()
//            ctx.alloc().buffer();
        }
    }
}
